package xx.iverson.navigation_manager.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import xx.iverson.navigation_manager.entity.NavCategory;
import xx.iverson.navigation_manager.entity.Navigation;
import xx.iverson.navigation_manager.entity.SiteConfig;
import xx.iverson.navigation_manager.service.NavCategoryService;
import xx.iverson.navigation_manager.service.NavigationService;
import xx.iverson.navigation_manager.service.SiteConfigService;
import xx.iverson.navigation_manager.util.UUIDUtil;

import java.io.File;
import java.io.IOException;
import java.util.List;
/**
 * xx.iverson.navigation_manager.controller.AdminController
 * 描述：
 * on 2025/9/11-下午4:27
 *
 * @author weijx
 */


@Controller
@RequestMapping("/admin")
public class AdminController {

    // 图片保存路径
    private static final String IMAGE_SAVE_PATH = "D:/navigation_image/";

    @Autowired
    private NavCategoryService categoryService;

    @Autowired
    private NavigationService navigationService;

    @Autowired
    private SiteConfigService siteConfigService;

    // 初始化保存图片的文件夹
    static {
        File dir = new File(IMAGE_SAVE_PATH);
        if (!dir.exists()) {
            dir.mkdirs();
        }
    }

    // 后台首页
    @GetMapping
    public String adminIndex(Model model) {
        // 获取网站配置
        SiteConfig siteConfig = siteConfigService.getSiteConfig();
        model.addAttribute("siteConfig", siteConfig);

        // 获取所有分类
        List<NavCategory> categories = categoryService.findAll();
        model.addAttribute("categories", categories);

        // 获取所有导航，包含分类名称
        List<Navigation> navigations = navigationService.findWithCategoryName();
        model.addAttribute("navigations", navigations);

        return "admin/index";
    }

    // 更新网站标题
    @PostMapping("/updateTitle")
    public String updateTitle(@RequestParam String siteTitle, RedirectAttributes redirectAttributes) {
        int result = siteConfigService.updateSiteTitle(siteTitle);
        if (result > 0) {
            redirectAttributes.addFlashAttribute("message", "网站标题更新成功");
        } else {
            redirectAttributes.addFlashAttribute("message", "网站标题更新失败");
        }
        return "redirect:/admin";
    }

    // 分类管理
    @PostMapping("/category/add")
    public String addCategory(@RequestParam String name, @RequestParam int sortOrder, RedirectAttributes redirectAttributes) {
        NavCategory category = new NavCategory();
        category.setName(name);
        category.setSortOrder(sortOrder);
        int result = categoryService.add(category);
        if (result > 0) {
            redirectAttributes.addFlashAttribute("message", "分类添加成功");
        } else {
            redirectAttributes.addFlashAttribute("message", "分类添加失败");
        }
        return "redirect:/admin";
    }

    @PostMapping("/category/update")
    public String updateCategory(@RequestParam int id, @RequestParam String name, @RequestParam int sortOrder, RedirectAttributes redirectAttributes) {
        NavCategory category = new NavCategory();
        category.setId(id);
        category.setName(name);
        category.setSortOrder(sortOrder);
        int result = categoryService.update(category);
        if (result > 0) {
            redirectAttributes.addFlashAttribute("message", "分类更新成功");
        } else {
            redirectAttributes.addFlashAttribute("message", "分类更新失败");
        }
        return "redirect:/admin";
    }

    @GetMapping("/category/delete/{id}")
    public String deleteCategory(@PathVariable int id, RedirectAttributes redirectAttributes) {
        int result = categoryService.delete(id);
        if (result > 0) {
            redirectAttributes.addFlashAttribute("message", "分类删除成功");
        } else {
            redirectAttributes.addFlashAttribute("message", "分类删除失败");
        }
        return "redirect:/admin";
    }

    // 导航管理
    @PostMapping("/navigation/add")
    public String addNavigation(
            @RequestParam int categoryId,
            @RequestParam String title,
            @RequestParam String url,
            @RequestParam int sortOrder,
            @RequestParam("imageFile") MultipartFile imageFile,
            RedirectAttributes redirectAttributes) {

        Navigation navigation = new Navigation();
        navigation.setCategoryId(categoryId);
        navigation.setTitle(title);
        navigation.setUrl(url);
        navigation.setSortOrder(sortOrder);

        // 处理图片上传
        if (!imageFile.isEmpty()) {
            try {
                String uuid = UUIDUtil.generateUUID();
                String originalFilename = imageFile.getOriginalFilename();
                String fileExtension = null;
                if (originalFilename != null) {
                    fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
                }
                String fileName = uuid + fileExtension;

                File dest = new File(IMAGE_SAVE_PATH + fileName);
                imageFile.transferTo(dest);

                navigation.setImageUuid(uuid + fileExtension);
            } catch (IOException e) {
                e.printStackTrace();
                redirectAttributes.addFlashAttribute("message", "图片上传失败");
                return "redirect:/admin";
            }
        }

        int result = navigationService.add(navigation);
        if (result > 0) {
            redirectAttributes.addFlashAttribute("message", "导航添加成功");
        } else {
            redirectAttributes.addFlashAttribute("message", "导航添加失败");
        }
        return "redirect:/admin";
    }

    @PostMapping("/navigation/update")
    public String updateNavigation(
            @RequestParam int id,
            @RequestParam int categoryId,
            @RequestParam String title,
            @RequestParam String url,
            @RequestParam int sortOrder,
            @RequestParam(value = "imageFile", required = false) MultipartFile imageFile,
            RedirectAttributes redirectAttributes) {

        Navigation navigation = navigationService.findById(id);
        if (navigation == null) {
            redirectAttributes.addFlashAttribute("message", "导航不存在");
            return "redirect:/admin";
        }

        navigation.setCategoryId(categoryId);
        navigation.setTitle(title);
        navigation.setUrl(url);
        navigation.setSortOrder(sortOrder);

        // 处理图片上传（如果有新图片）
        if (imageFile != null && !imageFile.isEmpty()) {
            try {
                // 删除旧图片
                if (navigation.getImageUuid() != null && !navigation.getImageUuid().isEmpty()) {
                    File oldFile = new File(IMAGE_SAVE_PATH + navigation.getImageUuid());
                    if (oldFile.exists()) {
                        oldFile.delete();
                    }
                }

                // 保存新图片
                String uuid = UUIDUtil.generateUUID();
                String originalFilename = imageFile.getOriginalFilename();
                String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
                String fileName = uuid + fileExtension;

                File dest = new File(IMAGE_SAVE_PATH + fileName);
                imageFile.transferTo(dest);

                navigation.setImageUuid(uuid + fileExtension);
            } catch (IOException e) {
                e.printStackTrace();
                redirectAttributes.addFlashAttribute("message", "图片上传失败");
                return "redirect:/admin";
            }
        }

        int result = navigationService.update(navigation);
        if (result > 0) {
            redirectAttributes.addFlashAttribute("message", "导航更新成功");
        } else {
            redirectAttributes.addFlashAttribute("message", "导航更新失败");
        }
        return "redirect:/admin";
    }

    @GetMapping("/navigation/delete/{id}")
    public String deleteNavigation(@PathVariable int id, RedirectAttributes redirectAttributes) {
        // 先获取导航信息，以便删除图片
        Navigation navigation = navigationService.findById(id);
        if (navigation != null && navigation.getImageUuid() != null && !navigation.getImageUuid().isEmpty()) {
            File imageFile = new File(IMAGE_SAVE_PATH + navigation.getImageUuid());
            if (imageFile.exists()) {
                imageFile.delete();
            }
        }

        int result = navigationService.delete(id);
        if (result > 0) {
            redirectAttributes.addFlashAttribute("message", "导航删除成功");
        } else {
            redirectAttributes.addFlashAttribute("message", "导航删除失败");
        }
        return "redirect:/admin";
    }
}

